import React, {Component} from 'react';
import Taro from '@tarojs/taro';
import {View, Image, Input, Text, Picker} from '@tarojs/components';
import {AtIcon} from 'taro-ui';
import {newHttp} from "../../utils/request";
import {
  FETCH_WIFI_SUPPLIERS,
  FETCH_WIFI_INSERT,
  FETCH_WIFI_UPDATE
} from "../../constants/api";
import WiFiCode from "./codeShow";
import "./index.scss";

const icon_wifi = "https://resource.ivcheng.com/upload/images/20220831/1661934771251_305.png";
const icon_lock = "https://resource.ivcheng.com/upload/images/20220831/1661934753425_827.png";
const icon_safe = "https://resource.ivcheng.com/upload/images/20220831/1661934707534_218.png";
const styleObj = {flex: 1, paddingLeft: "16Px", height: "inherit", lineHeight: "50px"};
const styleObj2 = {flex: 1, paddingLeft: "16Px", height: "inherit", lineHeight: "50px", color: "#999"};

export default class WiFiUpdate extends Component {
  constructor(props) {
    super(props);
    this.state = {
      deviceModel: "",
      clickNum: 0,
      wifiChecked: "",
      wifiIndex: 0,
      supplier_id: "",
      supplierChecked: "",
      supplierIndex: 0,
      supplierList: [],
      phoneWifiList: [],
      id: "",
      wifiName: "",
      wifiPwd: "",
      submiting: false,
      wifiCodeVisible: false,
      wifiCodeUrl: "",
      isiPhone: false
    };
  }

  UNSAFE_componentWillMount() {
    const reqParam = this.params;
    const {id, name: wifiName, pwd: wifiPwd, ssid: wifiIndex, userId} = reqParam;
    this.setState({id, wifiName, wifiPwd, wifiIndex});

    this.getSupplierList(userId);
  }

  componentDidShow() {
    const reqParam = this.params;
    const {id} = reqParam;
    const _this = this;
    const {clickNum} = this.state;

    if (this.state.phoneWifiList.length === 0) {
      Taro.showLoading({title: "请稍等", mask: true});
      // 修改时无需获取
      if (this.state.id) {
        Taro.hideLoading();
        return;
      }
      const showCancelBtn = clickNum > 0; // 用户点过一次确定之后

      wx.getSystemInfo({
        success(res) {
          const {model} = res;
          // iPhone 创建时
          if (model.indexOf("iPhone") > -1 && !id) {
            _this.setState({isiPhone: true});
            Taro.showModal({
              title: '提示',
              content: '请打开 [设置-无线局域网] 查看Wi-Fi列表, 然后返回小程序',
              showCancel: showCancelBtn,
              success: function (res) {
                if (res.confirm) {
                  _this.setState({
                    clickNum: clickNum + 1
                  }, () => {
                    _this.getWifiListOfPhone(model);
                  })
                }
              }
            })
          } else {
            // 仅创建
            !id && _this.getWifiListOfPhone(model);
          }
        }
      })
    }
  }

  params = Taro.getCurrentInstance().router.params

  // get wifi list of phone
  getWifiListOfPhone(model) {
    const _this = this;
    if (this.state.phoneWifiList.length > 0) return;

    wx.startWifi({
      success: (res) => {
        console.log("start : ", res)
        wx.getWifiList({
          success: (res) => {
            console.log("get : ", res)
            wx.onGetWifiList((result) => {
              console.log("res : ", result)
              const {wifiList} = result;
              _this.setState({
                phoneWifiList: wifiList,
                wifiIndex: wifiList[0].SSID
              }, () => {
                Taro.hideLoading();
              });
            })
          },
        })
      },
    })
  }

  // get supperlier list
  getSupplierList = async (userId) => {
    const userIdentity = await newHttp.catchGet(FETCH_WIFI_SUPPLIERS, {userId});
    if (userIdentity) {
      let supplierChecked = '';
      let supplier_id = '';
      const supplierIndex = Taro.getStorageSync('supplierIndexRecordWiFi') || 0;

      if (userIdentity.supplierUserList.length > 0) {
        supplierChecked = userIdentity.supplierUserList[supplierIndex].company;
        supplier_id = userIdentity.supplierUserList[supplierIndex].supplier_id;
        Taro.setStorageSync('supplierIndexRecordWiFi', supplierIndex);
      }

      this.setState({
        supplierIndex,
        supplierChecked,
        supplier_id,
        supplierList: userIdentity.supplierUserList
      })
    }
  }

  // change wifi
  onChangeWifi(e) {
    const {phoneWifiList} = this.state;
    const wifiIndex = Number(e.detail.value);
    const wifiChecked = phoneWifiList[wifiIndex].SSID;

    this.setState({wifiIndex, wifiChecked});
  }

  // change supplier
  onChange(e) {
    const {supplierList} = this.state;
    const supplierIndex = Number(e.detail.value);
    const supplier_id = supplierList[supplierIndex].supplier_id;
    const supplierChecked = supplierList[supplierIndex].company;

    this.setState({supplier_id, supplierIndex, supplierChecked}, async () => {
      Taro.setStorageSync('supplierIndexRecordWiFi', supplierIndex);
    })
  }

  // change name
  handleChangeName = e => {
    const {value} = e.detail;
    this.setState({wifiName: value});
  }
  // change password
  handleChangePwd = e => {
    const {value} = e.detail;
    this.setState({wifiPwd: value});
  }
  // close code layer
  handleCloseLayer = () => {
    this.setState({wifiCodeVisible: false, wifiCodeUrl: ""});
  }
  // submit
  handleSubmit = async () => {
    const _this = this;
    if (this.state.submiting) return;
    const {id, wifiName, wifiPwd, supplierChecked, supplier_id, wifiIndex, wifiChecked, isiPhone} = this.state;

    // 仅创建
    if (!id) {
      if (!wifiChecked) {
        Taro.showToast({title: "请选择WiFi", icon: "none"});
        return;
      }
    }
    /*if(!wifiName) {
      Taro.showToast({ title: "请输入WiFi名称", icon: "none" });
      return;
    }*/
    if (!wifiPwd) {
      Taro.showToast({title: "请输入WiFi密码", icon: "none"});
      return;
    }

    let params = {supplier_id, name: supplierChecked, pass: wifiPwd, ssid: wifiChecked}, fetchAPI = FETCH_WIFI_INSERT;
    if (!!id) {
      params.id = id;
      params.ssid = wifiIndex;
      fetchAPI = FETCH_WIFI_UPDATE;
    }

    Taro.showModal({
      title: '提示',
      content: '请确定密码输入正确',
      success: function (res) {
        if (res.confirm) {
          _this.doSubmit(fetchAPI, params);
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  }
  // do submit
  doSubmit = async (fetchAPI, params) => {
    /*params = {
      ...params,
      pass: "weichengzhijia",
      ssid: "wczj5"
    };*/
    this.setState({submiting: true}, () => {
      Taro.showLoading({
        title: "请稍等",
        mask: true
      })
    });
    const result = await newHttp.catchPost(fetchAPI, params, true, "needPage");
    if (result.data.msg === "创建成功" || result.data.msg === "修改成功") {
      Taro.showToast({
        title: result.data.msg,
        icon: "none",
        complete: res => {
          this.setState({
            submiting: false,
            wifiCodeVisible: true,
            wifiCodeUrl: result.data.wxVCodeImgStr
          }, () => {
            Taro.hideLoading();
          })
        }
      });
    } else {
      Taro.showToast({
        title: result.data.message,
        icon: 'none',
      });
      this.setState({
        submiting: false,
      }, () => {
        // Taro.hideLoading();
      })
    }
  }
  test = () => {
    /*Taro.navigateTo({
      url: '/other/scenicCard/index?uuid=8822dc6a5a4c4dedac0b24c4982d854a'
    })*/
  };

  render() {
    const {
      id,
      wifiIndex,
      wifiChecked,
      supplierChecked,
      supplierIndex,
      wifiName,
      wifiPwd,
      supplierList,
      submiting,
      wifiCodeVisible,
      wifiCodeUrl,
      phoneWifiList
    } = this.state;

    return (
      <View className='wifi-mng-page wifi-update-page'>
        {
          !id &&
          <View className='item bg-clr hg ct top'>
            <View className='header-bar'>
              <View className='head-picker'>
                {
                  !!supplierList && supplierList.length > 0 &&
                  <Picker value={supplierIndex} range={supplierList} rangeKey='company'
                    onChange={this.onChange.bind(this)}
                  >
                    <View className={supplierChecked ? 'picker' : 'picker off'}>
                      {supplierChecked ? '供应商: ' + supplierChecked : '请先选择供应商'}
                      <Text>切换</Text>
                    </View>
                  </Picker>
                }
              </View>
            </View>
          </View>
        }
        <View className='item wid update-tips'>
          <View className='tip-item'>
            <View className='ti-icon'>
              <Image src={icon_wifi} className='tip-img' />
            </View>
            <View>一键快速链接</View>
          </View>
          <View className='tip-item'>
            <View className='ti-icon'>
              <Image src={icon_lock} className='tip-img' />
            </View>
            <View>无须告知密码</View>
          </View>
          <View className='tip-item'>
            <View className='ti-icon'>
              <Image src={icon_safe} className='tip-img' />
            </View>
            <View>安全防蹭网</View>
          </View>
        </View>
        <View className='item mid update-data'>
          <View className='wifi-list'>
            {
              !id ?
                <View className='wl-item ud-item ud-item_pd'>
                  <View className='left-label'>WiFi列表</View>
                  <Picker
                    value={wifiIndex}
                    range={phoneWifiList}
                    rangeKey='SSID'
                    style={styleObj}
                    onChange={this.onChangeWifi.bind(this)}
                  >
                    <View className={wifiChecked ? 'picker' : 'picker off'}>
                      {
                        wifiChecked ?
                          wifiChecked
                          :
                          <Text style={{color: "#808080"}}>请选择WiFi</Text>
                      }
                    </View>
                  </Picker>
                </View>
                :
                <View className='wl-item ud-item ud-item_pd'>
                  <View className='left-label'>WiFi名称</View>
                  <Text style={styleObj2}>{wifiName}</Text>
                </View>
            }
            {/*<View className="wl-item ud-item ud-item_pd">
							<View className="left-label">WiFi名称</View>
							<Input
								name='wifiName'
								type='text'
								placeholder='请输入WiFi名称'
								placeholderClass="ipt-place-holder"
								value={wifiName}
								style={styleObj}
								onInput={this.handleChangeName}
							/>
						</View>*/}
            <View className='wl-item ud-item ud-item_pd'>
              <View className='left-label'>WiFi密码</View>
              <Input
                name='wifiPwd'
                type='text'
                placeholder='请输入WiFi密码'
                placeholderClass='ipt-place-holder'
                value={wifiPwd}
                style={styleObj}
                onInput={this.handleChangePwd}
              />
            </View>
            <View className='wid tip-text'>
              <AtIcon
                value='alert-circle'
                size='14'
                color='#F1A33A'
              />
              <Text className='text' onClick={this.test}>WiFi密码不会被共享, 请放心填写</Text>
            </View>
          </View>
        </View>
        <View
          className='item bg-clr ct submit-btn'
          onClick={this.handleSubmit}
        >一键生成WiFi码</View>

        {
          wifiCodeVisible &&
          <WiFiCode codeUrl={wifiCodeUrl} handleClose={this.handleCloseLayer} />
        }
      </View>
    )
  }
}
